package com.pro.controller;

import com.pro.pojo.*;
import com.pro.service.*;
import com.pro.utils.*;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/login")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private FastDFSClientUtil fsc;

    @Autowired
    private JsDeptAuthorityService jsDeptAuthorityService;

    @Autowired
    private JsUiserAuthorityService jsUiserAuthorityService;

    @Autowired
    private LoginRecordService loginRecordService;

    @Autowired
    private JsMenuDeptService jsMenuDeptService;

    @Autowired
    private RedisCatch redisCatch;


    //登录
    @RequestMapping("/login")
    public String login(HttpSession session){
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //获取当前时间
        String format = sdf1.format(new Date());
        //框架获取输入的账号和密码
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String name = authentication.getName();
        UserDetails userDetails = userDetailsService.loadUserByUsername(name);
        //调用方法传入账号与密码
        User user1 = userService.getUser(authentication.getName(), userDetails.getPassword());
        if(user1.getEnabled() == 2){
            return "login/loginBanned";
        }
        //登录时判断session的user是否有内容
        if(session.getAttribute("user")==null){
            //登录添加登录日志
            Map<String, Object> ipAndAddressUtils = addressUtils.getIPAndAddressUtils();
            LoginRecord loginRecord=new LoginRecord();
            loginRecord.setLoginIp((String) ipAndAddressUtils.get("ip"));
            loginRecord.setLoginAddress((String) ipAndAddressUtils.get("addr"));
            loginRecord.setLoginDate(format);
            loginRecordService.addLoginRecord(loginRecord);
        }
        if(user1!=null){
            session.setAttribute("user",user1);
        }
        return "login/index";
    }

    //退出
    @RequestMapping("/logout")
    public String login(){
        return "/login/login";
    }


    //获取所有数据
    @RequestMapping("/selectUserById")
    @ResponseBody
    public JsonData selectUserById(Integer id){
        User user = userService.selectUserById(id);
        return user != null ? JsonData.buildSuccess(user) : JsonData.buildError("服务器出错了");
    }

    //修改密码
    @RequestMapping("/updateUser")
    @ResponseBody
    public JsonData updateUser(User user){
        String s = MD5Util.md5(user.getPassword());
        user.setPassword(s);
        boolean updateUser = userService.updateUser(user);
        return updateUser? JsonData.buildSuccess(updateUser): JsonData.buildError("服务器出错了");
    }

    //修改头像
    @RequestMapping("/uploadUserHead")
    @ResponseBody
    public JsonData uploadUserHead(User user){
        boolean b = userService.uploadUserHead(user);
        return b ? JsonData.buildSuccess(b) : JsonData.buildError("服务器出错了");
    }


    //根据用户账号、用户姓名、所属部门、注册日期 查询所有用户
    @RequestMapping(value = "/getUsersByAccountNameDeptNameRegisterDate")
    @ResponseBody
    public JsonData getUsersByAccountNameDeptNameRegisterDate(User user){
        System.out.println(user);
        List<User> usersByAccountNameDeptNameRegisterDate = userService.getUsersByAccountNameDeptNameRegisterDate(user);
        HashMap<String, Object> map = new HashMap<>();
        map.put("data",usersByAccountNameDeptNameRegisterDate);
        map.put("msg","");
        map.put("code",0);
        return map.get("data") != null ? JsonData.buildSuccess(map) : JsonData.buildError("服务器出错了");
    }

    //更改用户启用、停用状态
    @RequestMapping(value = "/updateUserEnable")
    @ResponseBody
    public JsonData updateUserEnable(User user){
        boolean updateUserEnable = userService.updateUserEnable(user);
        return updateUserEnable ? JsonData.buildSuccess(updateUserEnable) : JsonData.buildError("服务器出错了");
    }

    //更改用户账号状态
    @RequestMapping(value = "/updateUserStatus")
    @ResponseBody
    public JsonData updateUserStatus(User user){
        boolean updateUserEnable = userService.updateUserStatus(user);
        return updateUserEnable ? JsonData.buildSuccess(updateUserEnable) : JsonData.buildError("服务器出错了");
    }
    //根据用户id查询后台人员表
    @RequestMapping(value = "/getUsersByDeptId")
    @ResponseBody
    public JsonData getUsersByDeptId(Integer deptId){
        List<User> usersByDeptId = userService.getUsersByDeptId(deptId);
        HashMap<String, Object> map = new HashMap<>();
        map.put("data",usersByDeptId);
        map.put("msg","");
        map.put("code",0);
        return map.get("data") != null ? JsonData.buildSuccess(map) : JsonData.buildError("服务器出错了");
    }

    @RequestMapping(value = "/uploadUserAcatar")
    @ResponseBody
    public JsonData updateUserAcatar(MultipartFile file, HttpServletRequest request) throws IOException {
        String fileName = null;
        String nameSuffix = null;
        String resAccessUrl = null;
        if(file.getSize() > 0) {
            fileName = file.getOriginalFilename();
            nameSuffix = fileName.substring(fileName.indexOf("."));
            fileName = "user" + new Date().getTime() + nameSuffix;
            //数据库文件路径
            String fileUrl = fsc.uploadFile(file);
            //前台传递路径
            resAccessUrl = fsc.getResAccessUrl(fileUrl);
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("code", 0);
        HashMap<String, Object> data = new HashMap<>();
        data.put("src", resAccessUrl);
        data.put("fileName", fileName);
        map.put("data", data);
        return map.get("data") != null ? JsonData.buildSuccess(map) : JsonData.buildError("上传失败");
    }

    //根据id修改用户信息
    @RequestMapping(value = "/updateUserMessage")
    @ResponseBody
    public JsonData updateUserMessage(User user){
        boolean updateUserMessage = userService.updateUserMessage(user);
        return updateUserMessage ? JsonData.buildSuccess("更改成功") : JsonData.buildError("上传失败");
    }

    //高级检索 根据手机号、身份证、启用状态、性别、邮箱、账户状态查询后台用户
    @RequestMapping(value = "/getUsersByEmailPhoneIdCardStatusSexEnabled")
    @ResponseBody
    public JsonData getUsersByEmailPhoneIdCardStatusSexEnabled(User user){
        List<User> usersByEmailPhoneIdCardStatusSexEnabled = userService.getUsersByEmailPhoneIdCardStatusSexEnabled(user);
        HashMap<String, Object> map = new HashMap<>();
        map.put("data",usersByEmailPhoneIdCardStatusSexEnabled);
        map.put("msg","");
        map.put("code",0);
        return map.get("data") != null ? JsonData.buildSuccess(map) : JsonData.buildError("服务器出错了");
    }
    //导入uesr
    @RequestMapping(value = "/importUser")
    @ResponseBody
    public JsonData importUser(MultipartFile file) throws IOException {
        String end = file.getOriginalFilename().substring(file.getOriginalFilename().indexOf("."));
        List<User> users = null;
        if(end.equals(".xls")){
            users = xlsExcel(file);
        }else{
            users = xlsxExcel(file);
        }
        boolean addUsers = userService.addUsers(users);
        HashMap<String, Object> map = new HashMap<>();
        map.put("code",0);
        map.put("data",users);

        return addUsers ? JsonData.buildSuccess(map) : JsonData.buildError("导入失败");
    }
    private List<User> xlsExcel(MultipartFile fil) throws IOException {
        ArrayList<User> list = new ArrayList<>();
        InputStream inputStream = fil.getInputStream();
        HSSFWorkbook workbook = new HSSFWorkbook(inputStream);
        HSSFSheet sheet= workbook.getSheetAt(0);
        User user = null;
        for (int rowNum = 1; rowNum <= sheet.getLastRowNum(); rowNum++) {
            HSSFRow row = sheet.getRow(rowNum);
            user = new User();
            user.setTrueName(row.getCell(0).toString());
            user.setSex(row.getCell(1).toString());
            user.setEmail(row.getCell(2).toString());
            user.setPhone(row.getCell(3).toString());
            user.setIdCard(row.getCell(4).toString());
            user.setBirthTime(row.getCell(5).toString());
            user.setAccount(row.getCell(6).toString());
            user.setWages(ExcelUtils.StrisInt(row.getCell(7).toString()));
            user.setPassword(row.getCell(8).toString());
            user.setFreestyle(row.getCell(9).toString());
            user.setRemark("后台添加");
            user.setAcatarUrl("http://101.200.239.240:80/group1/M00/00/01/rBmy-mGopO6ADk8eAAAEMngPrmE267.png");
            user.setRegisterTime(row.getCell(10).toString());
            user.setRegisterIp(row.getCell(11).toString());
            String enabled = row.getCell(12).toString();
            if("启用".equals(enabled)){
                user.setEnabled(1);
            }else if("停用".equals(enabled) || "未启用".equals(enabled)){
                user.setEnabled(2);
            }
            String status = row.getCell(13).toString();
            if("使用中".equals(status)){
                user.setStatus(1);
            }else if("已封禁".equals(status)){
                user.setStatus(2);
            }
        }
        list.add(user);
        return list;
    }
    private List<User> xlsxExcel(MultipartFile fil) throws IOException {
        ArrayList<User> list = new ArrayList<>();
        InputStream inputStream = fil.getInputStream();
        XSSFWorkbook Workbook = new XSSFWorkbook(inputStream);
        XSSFSheet sheet = Workbook.getSheetAt(0);
        User user = null;
        for (int rowNum = 1; rowNum <= sheet.getLastRowNum(); rowNum++) {
            XSSFRow row = sheet.getRow(rowNum);
            user = new User();
            user.setTrueName(row.getCell(0).toString());
            user.setSex(row.getCell(1).toString());
            user.setEmail(row.getCell(2).toString());
            user.setPhone(row.getCell(3).toString());
            user.setIdCard(row.getCell(4).toString());
            user.setBirthTime(row.getCell(5).toString());
            user.setAccount(row.getCell(6).toString());
            user.setWages(ExcelUtils.StrisInt(row.getCell(7).toString()));
            user.setPassword(row.getCell(8).toString());
            user.setFreestyle(row.getCell(9).toString());
            user.setRemark("后台添加");
            user.setAcatarUrl("http://101.200.239.240:80/group1/M00/00/01/rBmy-mGopO6ADk8eAAAEMngPrmE267.png");
            user.setRegisterTime(row.getCell(10).toString());
            user.setRegisterIp(row.getCell(11).toString());
            String enabled = row.getCell(12).toString();
            if("启用".equals(enabled)){
                user.setEnabled(1);
            }else if("停用".equals(enabled) || "未启用".equals(enabled)){
                user.setEnabled(2);
            }
            String status = row.getCell(13).toString();
            if("使用中".equals(status)){
                user.setStatus(1);
            }else if("已封禁".equals(status)){
                user.setStatus(2);
            }
        }
        list.add(user);
        return list;
    }
    //添加用户
    @RequestMapping(value = "/addUser")
    @ResponseBody
    public JsonData addUser(User user){
        user.setPassword(MD5Util.md5(user.getPassword()));
        boolean addUser = userService.addUser(user);
        addUserAuthority(user);
        return addUser ? JsonData.buildSuccess(user) : JsonData.buildError("服务器出错了");
    }

    private boolean addUserAuthority(User user){
        JsUiserAuthority jsUiserAuthority = new JsUiserAuthority();
        List<JsDeptAuthority> authoritys = jsDeptAuthorityService.getAuthoritysByDeptId(user.getDeptId());
        if(authoritys.size() == 0){
            return false;
        }
        LinkedList<Integer> authorityIds = new LinkedList<>();
        for (int i = 0; i < authoritys.size(); i++) {
            authorityIds.add(authoritys.get(i).getTrId());
        }
        jsUiserAuthority.setAuthorityIds(authorityIds);
        jsUiserAuthority.setUserId(user.getUserId());
        boolean addUserAuthority = jsUiserAuthorityService.addUserAuthority(jsUiserAuthority);
        return addUserAuthority;
    }

    //根据用户id查询用户信息
    @RequestMapping(value = "/getUserById")
    @ResponseBody
    public JsonData getUserById(Integer id){
        User user = userService.getUserById(id);
        return user != null ? JsonData.buildSuccess(user) : JsonData.buildError("服务器出错了");
    }



}
